package com.gzz.orchid.common.webmvc.util;

import com.gzz.orchid.common.core.util.IPUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 请求工具类 RequestUtil
 *
 * @author higmd
 */
public class ReqUtil {
    /**
     * 获取IP地址
     */
    public static String getIpAddress() {
        ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return IPUtil.getIpAddress(Objects.requireNonNull(req).getRequest());
    }

    public static String getUserAgent() {
        ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return IPUtil.getUserAgent(Objects.requireNonNull(req).getRequest());
    }

    /**
     * 获取访问终端的类型
     */
    public static String getTerminal() {
        ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (req != null) {
            request = req.getRequest();
            String userAgent = request.getHeader("user-agent");

            if (userAgent == null) {
                return "unknown";
            }
            if (userAgent.contains("Mobile")) {
                return "mobile";
            } else if (userAgent.contains("Windows") || userAgent.contains("Macintosh")) {
                return "pc";
            }
            return "other";
        } else {
            return "unknown";
        }
    }

}
